<?php

namespace app\shop\model;

use app\shop\model\Goods as GoodsModel;
use app\shop\model\GoodsSpec as GoodsSpecModel;
use app\shop\model\GoodsSpecValue as GoodsSpecValueModel;
use app\shop\model\Promotion as PromotionModel;
use think\Db;

class Order extends \ShopModel
{
    protected $table = 'sh_order';

    protected $pk = 'order_id';

    protected $autoWriteTimestamp = true;
    protected $updateTime = false;
    protected $createTime = 'create_at';

    protected $insert = ['order_sn'];


    public function customer(){
        return $this->belongsTo('Customer','customer_id')->field('customer_name');
    }

    public function orderGoods()
    {
        return $this->hasMany('OrderGoods', 'order_id');
    }

    public function orderLog(){
        return $this->hasMany('OrderLog','order_id');
    }

    public function orderAddress(){
        return $this->hasMany('OrderAddress','order_id');
    }

    protected function setOrderSnAttr()
    {
        return $this->generateOrderSn();
    }
    public function orderDb(){
        return Db::name('order');
}
    public function generateOrderSn()
    {
        $dateString = sprintf('%09d', time() - 1544745600);

        mt_srand((double) microtime() * 10000);
        $randString = sprintf('%05d', mt_rand(1, 99999));

        $orderNoTmp = substr($dateString, 4, 3)
            . substr($randString, 0, 2)
            . substr($dateString, 0, 2)
            . substr($dateString, 7)
            . substr($dateString, 2, 2)
            . substr($randString, 2);

        $count = $this->where([
            'order_sn' => $orderNoTmp,
        ])->count('order_sn');
        if ($count) return $this->generateOrderSn();

        return $orderNoTmp;
    }

    /**
     * 简单搜索
     * @return array
     */
    public function easySearch($params){

        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 20;

        $where = [];

        if(!empty($params['status'])){
            $where['order.status'] = ['in',$params['status']];
        }

        if(!empty($params['date'])){
            $filter_date = array_map(function($date){
                return strtotime($date);
            },$params['date']);
            $where['order.create_at'] = ['between',$filter_date];
        }
        
        if(!empty($params['query'])){
            $where['order.order_sn | customer.customer_name'] = ['like','%'.$params['query'].'%'];
        }

        $data = $this->alias('order')
        ->join('sh_customer customer','customer.customer_id = order.customer_id')
        ->field('customer.customer_name,order.*')
        ->where($where)
        ->page($page,$pageSize)->select();

        return $data;
    }

    /**
     * 高级搜索
     * @return array
     */
    public function search($params){

        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 20;

        $where = [];
        if(!empty($params['query'])){
            $where['order.order_sn | client.client_name'] = ['like','%'.$params['query'].'%'];
        }
        //订单号
        if(!(empty($params['order_sn']))){
            $where['order.order_sn'] = ['like','%'.$params['order_sn'].'%'];
        }
        //下单时间
        if(!empty($params['date'])){
            $filter_date = array_map(function($date){
                return strtotime($date);
            },$params['date']);
            $where['order.order_time'] = ['between',$filter_date];
        }
        //客户名称
        if(!empty($params['client_name'])){

            $where['client.client_name'] = ['like','%'.$params['client_name'].'%'];
        }
        //客户等级
        if(!empty($params['client_level'])){
            $where['client.client_level'] = $params['client_level'];
        }
        //收货地址
        if(!empty($params['address'])){
            $where['address.client_name | address.mobile |address.recipients'] = ['like','%'.$params['address'].'%'];
        }
        //商品信息
        if(!empty($params['goods'])){
            $where['order.search_goods'] = ['like','%'.$params['goods'].'%'];
        }
        //
        //制单人
        if(!empty($params['make'])){
            $where['order.make'] = ['like','%'.$params['make'].'%'];
        }
        //发货仓库
        if(!empty($params['warehouse_id'])){
            $where['order.warehouse_id'] = $params['warehouse_id'];
        }
        //打印状态
        if(isset($params['print_type'])){
            $where['order.print_type'] = $params['print_type'];
        }
        //打印状态
        if(isset($params['is_instead'])){
            $where['order.is_instead'] = $params['is_instead'];
        }
        //订单状态
        if(!empty($params['type'])){
            $where['order.type'] = ['in',$params['type']];
        }
        //收款状态
        if(!empty($params['gathering_type'])){
            $where['order.gathering_type'] = ['in',$params['gathering_type']];
        }

        $data = $this->alias('order')
            ->join('sh_client client','client.client_id = order.client_id','left')
            ->join('sh_order_address address','address.order_id = order.order_id','left')
            ->group('order.order_id')
            ->where($where)
            ->field('order.*,client.client_name name,address.*')
            ->page($page,$pageSize)->select();

        $total = $this->alias('order')
            ->join('sh_client client','client.client_id = order.client_id','left')
            ->join('sh_order_address address','address.order_id = order.order_id','left')
            ->group('order.order_id')
            ->where($where)
            ->field('order.order_id')
            ->count();
            
        return [
            'data' => $data,
            'pager' => [
                'page' => $page,
                'pageSize' => $pageSize,
                'total' => $total
            ]
        ];

    }

    //获取状态翻译
    public function getDeliverGoodsStatusTrans($status){
        $all_status = array(
            0 => '待发货',
            1 => '部分发货',
            2 => '已发货',

        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知';
    }
    //获取状态翻译
    public function getWarehouseStatusTrans($status){
        $all_status = array(
            0 => '备货中',
            1 => '部分出库',
            2 => '已出库',

        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知';
    }
    //获取发票类型翻译
    public function getBillTrans($bill){
        $all_bull = array(
            0 => '不开发票',
            1 => '普通发票',
            2 => '增值税发票'
        );
        return !empty($all_bull[$bill]) ? $all_bull[$bill] : '未知';
    }
    //获取状态翻译
    public function getStatusTrans($status){
        $all_status = array(
            0 => '待订单审核',
            1 => '待财务审核',
            2 => '待出库审核',
            3 => '待发货确认',
            4 => '待收货确认',
            5 => '已完成',
            6 => '已作废'
        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知'; 
    }

    //财务翻译
    public function getFinanceStatusTrans($status){
        $all_status = array(
            0 => '收款待审核',
            1 => '未收款',
            2 => '已收款',

        );
        return !empty($all_status[$status]) ? $all_status[$status] : '未知';
    }

    //获取订单详情
    public function getOrderDetail($id){

        $orderDb = $this->orderDb();
        $order = $orderDb->alias('a')->join('sh_client c','a.client_id=c.client_id')->where('order_id',$id)->field('a.*,c.client_name')->find();
        $order['type_trans'] = $this->getStatusTrans($order['type']);//订单状态翻译
        $order['delivery_time'] = date('Y-m-d H:i:s',$order['delivery_time']);
        $order['order_time'] = date('Y-m-d H:i:s',$order['order_time']);
        $order['gathering_type']  = $this->getFinanceStatusTrans($order['gathering_type']);//财务翻译

        //订单商品
        $OrderGoods = new OrderGoods();
        $OrderGoodsDb = $OrderGoods->OrderGoodsDb();
        $goods = $OrderGoodsDb->alias('a')->join('sh_goods_unit g','a.unit_id = g.unit_id','left')->where('a.order_id',$id)->field('a.*,g.unit_name')->select();
        
        foreach($goods as &$g){

            if(!empty($g['promotion_id'])){

                $promotion = Db::name('promotion')->where('promotion_id',$g['promotion_id'])->field('promotion_cate,promotion_title,promotion_type,promotion_rule,promotion_detail')->find();

                $promotion['promotion_detail'] = json_decode($promotion['promotion_detail']);

                $g['promotion'] = $promotion;

            }

        }

        
        //订单优惠
        $order_discount = Db::name('order_discount_detail')->where('order_id',$id)->value('desc');

        if(!empty($order_discount)){

            $order_discount = unserialize($order_discount);

            foreach($order_discount as $o){
                
                $order_promotion = Db::name('promotion')->where('promotion_id',$o['promotion_id'])->field('promotion_title,promotion_cate,promotion_rule')->find();

                $order_promotion['discount'] = $o['discount'];

                $order['promotion'][] = $order_promotion;

            }

        }

        $OrderAccessoryModel = new OrderAccessory();
        $OrderAccessoryDb = $OrderAccessoryModel->OrderAccessoryDb();
        $Accessory = $OrderAccessoryDb->alias('a')->join('sh_accessory c','a.accessory_id = c.accessory_id')->where('a.order_id',$id)->field('accessory_url url,accessory_name name')->select();
        
        foreach($Accessory as &$acc){
            $acc['url'] = $acc['url'].'|'.$acc['name']; 
        }

        $OrderAddress = new OrderAddress();
        $OrderAddressDb = $OrderAddress->OrderAddressDb();
        $address = $OrderAddressDb->where('order_id',$id)->order('save_time desc')->find();
        $OrderBill = new OrderBill();
        $OrderBillDb = $OrderBill->OrderBillDb();
        $Bill = $OrderBillDb->where('order_id',$id)->find();
        //获取订单操作日志
        $OrderLog = new OrderLog();
        $OrderLogDb = $OrderLog->OrderLogDb();
        $log = $OrderLogDb->where('order_id',$id)->order('create_at desc')->select();
        foreach ($log as $k=>$v){
            $log[$k]['create_at'] = date('Y-m-d H:i:s',$log[$k]['create_at']);
        }
        return [
            'order' => $order,//订单详情
            'goods' => $goods,//商品数据
            'address' => $address,//订单地址
            'bill' => $Bill,//发票数据
            'accessory' => $Accessory,//附件
            'log'=>$log//获取订单操作日志
        ];
    }


    public function get_discount($client_id,$goods,$flag){

        $discount = $this->getpromotion($client_id);
        
        $goods_price = $this->getPrice($client_id,$goods);
       
        $total = 0;

        if($flag){

            foreach($goods_price as $g){

                $total += $g['price'] * $g['quantity'];

            }

            return [
                'goods' => $goods_price,
                'total' => $total
            ];

        }

        $tmp_goods_id = array_keys($goods_price);

        //单品优惠
        foreach($discount['product'] as $goods_discount){
            
            if($goods_discount['promotion_rule'] === 4){

            }else{
                
                if(isset($goods_price[$goods_discount['promotion_goods']])){
                    
                    unset($tmp_goods_id[array_search($goods_discount['promotion_goods'],$tmp_goods_id)]);

                    $tmp_goods = $goods_price[$goods_discount['promotion_goods']];
                    
                    $tmp_total = isset($tmp_goods['real_quantity']) ? $tmp_goods['real_quantity'] : $tmp_goods['quantity'];
                   
                    $max = 0;

                    $max_full = 0;
                    
                    foreach($goods_discount['promotion_detail'] as $detail){
                        
                        if($tmp_total >= $detail['full'] && $detail['full'] > $max_full){
                            
                            $max_full = $detail['full'];

                            $max = $detail['reduction'];
    
                        }else{
    
                            continue;
    
                        }
    
                    }
                    
                    if($max){

                        if($goods_discount['promotion_rule'] === 5){
                        
                            $goods_price[$goods_discount['promotion_goods']]['special_price'] = $max;

                        }
    
                        if($goods_discount['promotion_rule'] === 6){
                            
                            $goods_price[$goods_discount['promotion_goods']]['special_price'] = $goods_price[$goods_discount['promotion_goods']]['price'] * ($max / 100);

                        }

                        $goods_price[$goods_discount['promotion_goods']]['promotion_id'] = $goods_discount['promotion_id'];

                    }

                    $total += $goods_price[$goods_discount['promotion_goods']]['special_price'] * $goods_price[$goods_discount['promotion_goods']]['quantity'];
                   
                }else{
                    
                    continue;
    
                }

            }

        }

        $order_discount = [];

        //组合优惠
        foreach($discount['group'] as $group_discount){

            $group_goods_ids = explode(',',$group_discount['group_goods']);

            $tmp_group_qty = 0;
            $tmp_group_total = 0;

            foreach($tmp_goods_id as $k => $v){

                if(in_array($v,$group_goods_ids)){

                    $tmp_qty = isset($goods_price[$v]['real_quantity']) ? $goods_price[$v]['real_quantity'] : $goods_price[$v]['quantity'];

                    $tmp_group_qty += $tmp_qty;
                    
                    $tmp_group_total += $goods_price[$v]['price'] * $goods_price[$v]['quantity'];

                    $total += $tmp_group_total;
                    
                    $goods_price[$v]['promotion_id'] = $group_discount['promotion_id'];

                    unset($tmp_goods_id[$k]);

                }else{

                    continue;

                }

            }

            $max = 0;

            $max_full = 0;
            
            foreach($group_discount['promotion_detail'] as $detail){

                //数量
                if($group_discount['promotion_type'] === 1){

                    if($tmp_group_qty >= $detail['full'] && $detail['full'] > $max_full){

                        $max_full = $detail['full'];

                        $max = $detail['reduction'];

                    }else{

                        continue;

                    }

                }

                //金额
                if($group_discount['promotion_type'] === 2){

                    if($tmp_group_total >= $detail['full'] && $detail['full'] > $max_full){

                        $max_full = $detail['full'];

                        $max = $detail['reduction'];

                    }else{

                        continue;

                    }

                }

            }
            
            if($max){

                //满赠
                if($group_discount['promotion_rule'] === 1){

                }

                //满减
                if($group_discount['promotion_rule'] === 2){
                    
                    $total -= $max;

                    $order_discount[] = [
                        'promotion_id' => $group_discount['promotion_id'],
                        'discount' => $max
                    ];

                } 

                //满折
                if($group_discount['promotion_rule'] === 3){

                    $percent_total = $tmp_group_total * ( 1 - $max / 100);

                    $total -= round($percent_total,2);

                    $order_discount[] = [
                        'promotion_id' => $group_discount['promotion_id'],
                        'discount' => round($percent_total,2)
                    ];

                }

                //买赠
                if($group_discount['promotion_rule'] === 4){



                }

                //直降
                if($group_discount['promotion_rule'] === 5){

                    foreach($group_goods_ids as $id){

                        if(isset($goods_price[$id])){

                            $goods_price[$id]['special_price'] = $max;

                            $total += $goods_price[$id]['special_price'] * $goods_price[$id]['quantity'];

                        }

                    }

                }
                
                //打折
                if($group_discount['promotion_rule'] === 6){

                    foreach($group_goods_ids as $id){

                        if(isset($goods_price[$id])){

                            $goods_price[$id]['special_price'] = $goods_price[$id]['price'] * ($max / 100);

                            $total += $goods_price[$id]['special_price'] * $goods_price[$id]['quantity'];

                        }

                    }

                }

            }

        }

        foreach($tmp_goods_id as $t){
            $total += $goods_price[$t]['price'] * $goods_price[$t]['quantity'];
        }

        //订单优惠

        $tmp_max = 0;

        $tmp_max_full = 0;

        foreach($discount['order']['promotion_detail'] as $detail){

            if($total >= $detail['full'] && $detail['full'] > $tmp_max_full){

                $tmp_max_full = $detail['full'];

                $tmp_max = $detail['reduction'];

            }else{

                continue;

            }

        }

        //满赠
        if($discount['order']['promotion_rule'] === 1){



        }

        //满减
        if($discount['order']['promotion_rule'] === 2){

            $total = $total - $tmp_max;

            $order_discount[] = [
                'promotion_id' => $discount['order']['promotion_id'],
                'discount' => $tmp_max
            ];

        }


        //满折
        if($discount['order']['promotion_rule'] === 3){

            $percent_total = $total * (1 - $tmp_max / 100);

            $total -= round($percent_total,2);

            $order_discount[] = [
                'promotion_id' => $discount['order']['promotion_id'],
                'discount' => round($percent_total,2)
            ];

        }
        
        $final = [
            'goods' => $goods_price,
            'order_discount' => $order_discount,
            'total' => $total
        ];
        
        return $final;
    }

    public function getpromotion($client_id){
        $Pro=new PromotionModel();
        $level_id=db("client")->where(["client_id"=>$client_id])->value("level_id");
        $now=date("Y-m-d H:i:s");
        $wherec="cus_list=$client_id or cus_list like '{$client_id},%' or cus_list like '%,{$client_id}' or cus_list like '%,{$client_id},%'";
        $whered="start_time<='{$now}' and end_time>'$now' ";

        $order=db("promotion")->where($wherec)->where($whered)->where("promotion_cate=2")->field("promotion_id,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->find();
        if(!$order){
            $order=db("promotion")->where(["cus_level"=>$level_id])->where($whered)->where("promotion_cate=2")->field("promotion_id,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->find();
        }
        if(!$order){
            $order=db("promotion")->where(["cus_level"=>9999])->where($whered)->where("promotion_cate=2")->field("promotion_id,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->find();
        }
        $order["promotion_detail"]=json_decode($order["promotion_detail"],true);
        $data["order"]=$order;
        $pc=db("promotion")->where($wherec)->where($whered)->where("promotion_cate=1")->field("promotion_id,promotion_goods,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
        $pc1=db("promotion")->where(["cus_level"=>$level_id])->where($whered)->where("promotion_cate=1")->field("promotion_id,promotion_goods,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
        $pc2=db("promotion")->where(["cus_level"=>9999])->where($whered)->where("promotion_cate=1")->field("promotion_id,promotion_goods,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
        $pids=[];
        $product=[];
        foreach ($pc as $k => $v) {
            # code...
            $pc[$k]["promotion_detail"]=json_decode($pc[$k]["promotion_detail"],true);
            $pids[]=$v["promotion_goods"];
            $product=$pc[$k];
        }
        foreach ($pc1 as $k => $v) {
            # code...
            if(!in_array($v["promotion_goods"],$pids)){
                $pc1[$k]["promotion_detail"]=json_decode($pc1[$k]["promotion_detail"],true);
                $pids[]=$v["promotion_goods"];
                $product[]=$pc1[$k];
            }
            
        }
        foreach ($pc2 as $k => $v) {
            # code...
            if(!in_array($v["promotion_goods"],$pids)){
                $pc2[$k]["promotion_detail"]=json_decode($pc2[$k]["promotion_detail"],true);
                $pids[]=$v["promotion_goods"];
                $product[]=$pc2[$k];
            }
            
        }
        $data["product"]=$product;
        $gc=db("promotion")->where($wherec)->where($whered)->where("promotion_cate=3")->field("promotion_id,group_goods,group_goods_count,promotion_type,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
        $gc1=db("promotion")->where(["cus_level"=>$level_id])->where($whered)->where("promotion_cate=3")->field("promotion_id,group_goods,group_goods_count,promotion_type,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
        $gc2=db("promotion")->where(["cus_level"=>9999])->where($whered)->where("promotion_cate=3")->field("promotion_id,group_goods,group_goods_count,promotion_type,promotion_title,promotion_rule,promotion_detail,start_time,end_time")->select();
        $pidgs=[];
        $group=[];
        foreach ($gc as $k => $v) {
            # code...
            $gc[$k]["promotion_detail"]=json_decode($gc[$k]["promotion_detail"],true);
            $p=explode(',',$v["group_goods"]);
            for($i=0;$i<count($p);$i++){
                $pidgs[]=$p[$i];
            }
            $group[]=$gc[$k];
        }
        foreach ($gc1 as $k => $v) {
            # code...
            $p=explode(',',$v["group_goods"]);
            $flag=0;
            for($i=0;$i<count($p);$i++){
                if(in_array($p[$i],$pidgs)){
                    $flag=1;break;
                }
            }
            if($flag==0){
                $gc1[$k]["promotion_detail"]=json_decode($gc1[$k]["promotion_detail"],true);

                for($i=0;$i<count($p);$i++){
                    $pidgs[]=$p[$i];
                }
                $group[]=$gc1[$k];
            }
            
        }
        foreach ($gc2 as $k => $v) {
            # code...
            $p=explode(',',$v["group_goods"]);
            $flag=0;
            for($i=0;$i<count($p);$i++){
                if(in_array($p[$i],$pidgs)){
                    $flag=1;break;
                }
            }
            if($flag==0){
                $gc2[$k]["promotion_detail"]=json_decode($gc2[$k]["promotion_detail"],true);

                for($i=0;$i<count($p);$i++){
                    $pidgs[]=$p[$i];
                }
                $group[]=$gc2[$k];
            }
            
        }
        $data["group"]=$group;

        return $data;
    }


    public function getPrice($client_id,$goods){

        $final = [];

        foreach($goods as &$v){
            
            $goods_data = Db::name('goods')->field('goods_id,goods_name,is_units,is_client_price,goods_sn,goods_img,keywords')->where('goods_id',$v['goods_id'])->find();

            $v['goods_name'] = $goods_data['goods_name'];
            $v['goods_sn'] = $goods_data['goods_sn'];
            $v['goods_img'] = $goods_data['goods_img'];
            $v['keywords'] = $goods_data['keywords'];

            if($goods_data['is_client_price']){

                $client_price = Db::name('goods_client_price')->where('client_purchase',1)->where('goods_id',$v['goods_id'])->where('client_id',$client_id)->select();

            }

            $client_level = Db::name('client')->where('client_id',$client_id)->value('level_id');

            $level_price = Db::name('goods_level_price')->where('level_purchase',1)->where('goods_id',$v['goods_id'])->where('level_id',$client_level)->find();

            $unit_data = Db::name('goods_units')->where('goods_id',$v['goods_id'])->find();

            if($goods_data['is_units'] !== 1 || $v['unit_id'] == $unit_data['initial_unit_id']){

                if(!empty($client_price)){

                    $v['price'] = $client_price['client_price1'];

                }elseif(!empty($level_price)){

                    $v['price'] = $level_price['level_price1'];

                }else{

                    $v['price'] = $unit_data['initial_unit_price'];

                }

            }else{

                if($v['unit_id'] == $unit_data['extra1_unit_id']){

                    if(!empty($client_price)){

                        $v['price'] = $client_price['client_price2'];
    
                    }elseif(!empty($level_price)){
    
                        $v['price'] = $level_price['level_price2'];
    
                    }else{
    
                        $v['price'] = $unit_data['extra1_unit_price'];
    
                    }

                    $v['real_quantity'] = $unit_data['extra1_unit_ratio'] * $v['quantity'];

                }

                if($v['unit_id'] == $unit_data['extra2_unit_id']){

                    if(!empty($client_price)){

                        $v['price'] = $client_price['client_price3'];
    
                    }elseif(!empty($level_price)){
    
                        $v['price'] = $level_price['level_price3'];
    
                    }else{
    
                        $v['price'] = $unit_data['extra2_unit_price'];
    
                    }

                    $v['real_quantity'] = $unit_data['extra2_unit_ratio'] * $v['quantity'];

                }

            }

            $final[$v['goods_id']] = $v;

        }   

        return $final;

    }

}
